package com.example.demo.Controller;

import com.example.demo.Common.ResultData;
import com.example.demo.Entity.Customer;
import com.example.demo.Entity.Order;
import com.example.demo.Entity.Product;
import com.example.demo.Entity.Vendor;
import com.example.demo.Param.*;
import com.example.demo.Service.OrderService;
import com.example.demo.Service.ProductService;
import com.example.demo.Service.UserService;
import com.example.demo.Service.VendorService;
import com.example.demo.Util.ExcelReader;
import com.example.demo.Util.ExcelWriter;
import com.example.demo.VO.ExcelDataVO;
import com.example.demo.VO.ExcelUpdateDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private ProductService productService;

    @Resource
    private UserService userService;

    @Resource
    private VendorService vendorService;

    private static final Logger logger = LoggerFactory.getLogger(VendorController.class);

    @GetMapping("/order/getAll")
    public List<Order> getOrders(){
        return this.orderService.getAll();
    }

    @PostMapping("/order/del")
    @ResponseBody
    public ResultData deleteOrder(@RequestBody String id) throws JSONException {
        JSONArray jsonArray = null;
        jsonArray = new JSONArray("["+id+"]");
        System.out.println(jsonArray.getJSONObject(0).get("id"));
        String realId = jsonArray.getJSONObject(0).get("id").toString();
        Long oid = Long.valueOf(realId);
        this.orderService.deleteOrder(oid);
        return ResultData.success();
    }


    @PostMapping("/orderAdd")
    @ResponseBody
    public ResultData addOrder(@RequestBody OrderInsertParam orderInsertParam){
        //System.out.println(addressReq.getStreetName());
        //System.out.println(addressReq.getTel());
       // Address address = this.addressService.createOne(addressReq);
        Order order = this.orderService.createOne(orderInsertParam);
       // System.out.println(address.getStreetName());
       // System.out.println(address.getTel());
        return ResultData.success();
    }

    @PostMapping("/order/udate")
    @ResponseBody
    public ResultData uodateOrder(@RequestBody OrderUpdateParam orderUpdateParam){
        //System.out.println(addressReq.getStreetName());
        //System.out.println(addressReq.getTel());
        // Address address = this.addressService.createOne(addressReq);
        this.orderService.updateOrder(orderUpdateParam);
        // System.out.println(address.getStreetName());
        // System.out.println(address.getTel());
        return ResultData.success();
    }


    @GetMapping("/order/purchase")
    public ResultData purchase(){
        Boolean isRisky = riskControl();
        if(isRisky == false){
            return ResultData.fail();
        }
        return ResultData.success();
    }

    @GetMapping("/order/downloadList")
    public ResultData downloadList() {
            List<Order> orders = this.orderService.getAll();
            List<ExcelDataVO> dataVOList = new ArrayList<>();
            for(int i = 0; i < orders.size(); i++){
                ExcelDataVO excelDataVO = new ExcelDataVO();
                Customer findedCustomer = this.userService.findCustomerById(orders.get(i).getCustomerId());
                Product findedProduct = this.productService.getProductByProducName(orders.get(i).getProductname());
                excelDataVO.setCustomername(findedCustomer.getCustomername());
                excelDataVO.setProductname(orders.get(i).getProductname());
                excelDataVO.setQuantity(orders.get(i).getQuantity());
                excelDataVO.setSku(orders.get(i).getSku());
                excelDataVO.setSpu(orders.get(i).getSpu());
                Long totalPrice = (long) (findedProduct.getProductprice()*orders.get(i).getQuantity());
                excelDataVO.setTotalprice(totalPrice);
                dataVOList.add(excelDataVO);
            }

            // 写入数据到工作簿对象内
            Workbook workbook = ExcelWriter.exportData(dataVOList);

            // 以文件的形式输出工作簿对象
            FileOutputStream fileOut = null;
            try {
                String exportFilePath = "D:\\ordersystem\\download\\order.xlsx";
                File exportFile = new File(exportFilePath);
                if (!exportFile.exists()) {
                    exportFile.createNewFile();
                }

                fileOut = new FileOutputStream(exportFilePath);
                workbook.write(fileOut);
                fileOut.flush();
            } catch (Exception e) {
                log.info("输出Excel时发生错误，错误原因：" + e.getMessage());
            } finally {
                try {
                    if (null != fileOut) {
                        fileOut.close();
                    }
                    if (null != workbook) {
                        workbook.close();
                    }
                } catch (IOException e) {
                    log.info("关闭输出流时发生错误，错误原因：" + e.getMessage());
                }
            }
        String startPath = "D:\\ordersystem\\download\\order.xlsx";
        String endPath = "D:\\ordersystem\\upload\\order.xlsx";
        copyFile(startPath, endPath);
        return ResultData.success();
    }

    @GetMapping("/order/uploadList")
    public ResultData uploadList() throws IOException {
        //String startPath = "D:\\ordersystem\\download\\order.xlsx";

        String endPath = "D:\\ordersystem\\upload\\order.xlsx";
        //Desktop.getDesktop().open(new File(endPath));
        //copyFile(startPath, endPath);
        // 设定Excel文件所在路径
        String excelFileName = endPath;
        // 读取Excel文件内容
        List<ExcelUpdateDataVO> readResult = ExcelReader.readExcel(excelFileName);
        for(ExcelUpdateDataVO excelUpdateDataVO : readResult){
            VendorInsertParam vendorInsertParam = new VendorInsertParam();
            vendorInsertParam.setVendorname(excelUpdateDataVO.getVendorname());
            vendorInsertParam.setVendortel(excelUpdateDataVO.getVendortel());
            vendorInsertParam.setVendoraddress(excelUpdateDataVO.getVendoraddress());
            Vendor vendor = this.vendorService.createOne(vendorInsertParam);
        }
        return ResultData.success();
    }

    public boolean riskControl(){
        List<Order> orders = this.orderService.getAll();
        for(Order order: orders){
            //判断客户ID是否小于等于0或者产品名为空
            if(order.getCustomerId() <= 0 || order.getProductname() == null){
                return false;
            }
            Product findedProduct = this.productService.getProductByProducName(order.getProductname());
            if(findedProduct == null){
                return false;
            }
            if(order.getQuantity() > findedProduct.getProductstock()){
                return false;
            }
        }
        return true;
    }

    public void copyFile(String strOldpath,String strNewPath) {
        try {

            File fOldFile = new File(strOldpath);
            if (fOldFile.exists()) {
                int bytesum = 0;
                int byteread = 0;
                InputStream inputStream = new FileInputStream(fOldFile);
                FileOutputStream fileOutputStream = new FileOutputStream(strNewPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inputStream.read(buffer)) != -1) {
                    bytesum += byteread; //这一行是记录文件大小的，可以删去
                    fileOutputStream.write(buffer, 0, byteread);//三个参数，第一个参数是写的内容，
                    //第二个参数是从什么地方开始写，第三个参数是需要写的大小
                }
                inputStream.close();
                fileOutputStream.close();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("复制单个文件出错");
            e.printStackTrace();
        }
    }

    @PostMapping("/order/search")
    @ResponseBody
    public List<Order> searchOrder(@RequestBody SearchOrderParam searchOrderParam){
        Long customerId = searchOrderParam.getCustomerId();
        List<Order> orders = new ArrayList<>();
        if(customerId==null){
            orders = this.orderService.getAll();
            return orders;
        }
        orders = this.orderService.searchOrder(customerId);
        return orders;
    }

}
